package management.system.view.servlet;


import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import management.system.model.bean.IdeaDTO;
import management.system.model.bean.UsuarioDTO;
import management.system.model.services.IdeaService;
import management.system.model.services.UsuarioService;
import management.system.utils.Constants;

/**
 * Servlet implementation class ServletIdea
 */
@WebServlet("/idea")
//@MultipartConfig(maxFileSize = 16177215)    // upload file's size up to 16MB
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB 
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)   // 50MB

public class ServletIdea extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */

	
	
    public ServletIdea() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String metodo = request.getParameter("metodo");
		//request.getSession().setAttribute("errorMessage", null);

		if(metodo.equals("INSERTA")){
			insertIdea(request, response);
		}else if(metodo.equals("EDITA")){
			updateIdea(request, response);
		}else if(metodo.equals("ELIMINA")){
			deleteIdea(request, response);
		}else if(metodo.equals("BUSCA")){
			findIdea(request, response);
		}else if(metodo.equals("FILTRO")){
			System.out.println("Ingreso Filtro");
			listFiltroIdea(request, response);
		}else if(metodo.equals("PUBLICADO")){
			System.out.println("Ingreso Filtro");
			listPublicadosIdea(request, response);
		}else if(metodo.equals("ESCOGE")){
			buscaIdea(request, response);
		}else if(metodo.equals("ESCOGEPUBLICADO")){
			buscaPublicadoIdea(request, response);
		}else if(metodo.equals("EVALUAR")){
			updateEvaluarIdea(request, response);
		}else{
			System.out.println("Ingreso lista");
			listIdea(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String metodo = request.getParameter("metodo");
		
		if(metodo.equals("INSERTA")){
			insertIdea(request, response);
		}else if(metodo.equals("EDITA")){
			updateIdea(request, response);
		}else if(metodo.equals("ELIMINA")){
			deleteIdea(request, response);
		}else if(metodo.equals("BUSCA")){
			findIdea(request, response);
		}else if(metodo.equals("FILTRO")){
			System.out.println("Ingreso Filtro");
			listFiltroIdea(request, response);
		}else if(metodo.equals("PUBLICADO")){
			System.out.println("Ingreso Filtro");
			listPublicadosIdea(request, response);
		}else if(metodo.equals("ESCOGE")){
			buscaIdea(request, response);
		}else if(metodo.equals("ESCOGEPUBLICADO")){
			buscaPublicadoIdea(request, response);
		}else if(metodo.equals("EVALUAR")){
			updateEvaluarIdea(request, response);
		}else{
			System.out.println("Ingreso Listado");
			listIdea(request, response);
		}
	}
	
	protected void insertIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		IdeaService ideaService = new IdeaService();
		IdeaDTO dto = new IdeaDTO();
		Integer result = null;

		
        String appPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String savePath = appPath + File.separator + Constants.SAVE_DIR;
        
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }
        System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());


        String fileName = getFileName(request.getPart("fileImage"));
        request.getPart("fileImage").write(savePath + File.separator + fileName + File.separator);

		try {

			if(ideaService.getTitulo(request.getParameter("txtTitulo"))>0){

				//request.getSession().setAttribute("errorMessage", flag);
				Constants.VALIDATE = 1;
				//getServletContext().getRequestDispatcher("/jsp/nuevaIdea.jsp").forward(request, response);
				response.sendRedirect("jsp/nuevaIdea.jsp");
			}else{
				
				dto.setPerfilId(Constants.usuarioDTO.getPerfilId());
				dto.setTitulo(request.getParameter("txtTitulo"));
				dto.setDescripcion(request.getParameter("txtDescripcion"));
				dto.setPalabraClave1(request.getParameter("txtPalabraClave1"));
				dto.setPalabraClave2(request.getParameter("txtPalabraClave2"));
				dto.setPalabraClave3(request.getParameter("txtPalabraClave3"));
				dto.setPalabraClave4(request.getParameter("txtPalabraClave4"));
				dto.setImagen(fileName);
				dto.setUsuarioId(Constants.usuarioDTO.getUsuarioId());
				result = ideaService.insertIdea(dto);
						
				if(result >0){
				
					Constants.VALIDATE = 0;
					listIdea(request, response);
					System.out.println("Registro exitosamente!");
				}				
			}				

		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		} 
		
		
	}

	protected void updateIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		IdeaService ideaService = new IdeaService();
		IdeaDTO dto = new IdeaDTO();
		Integer result = null;

		
        String appPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String savePath = appPath + File.separator + Constants.SAVE_DIR;
        
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }
        System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());


        String fileName = getFileName(request.getPart("fileImage"));
        request.getPart("fileImage").write(savePath + File.separator + fileName + File.separator);

		try {


				dto.setIdeaId(Integer.parseInt(request.getParameter("codigo")));
				dto.setPerfilId(Constants.usuarioDTO.getPerfilId());
				dto.setTitulo(request.getParameter("txtTitulo"));
				dto.setDescripcion(request.getParameter("txtDescripcion"));
				dto.setPalabraClave1(request.getParameter("txtPalabraClave1"));
				dto.setPalabraClave2(request.getParameter("txtPalabraClave2"));
				dto.setPalabraClave3(request.getParameter("txtPalabraClave3"));
				dto.setPalabraClave4(request.getParameter("txtPalabraClave4"));
				dto.setImagen(fileName);
				dto.setUsuarioId(Constants.usuarioDTO.getUsuarioId());
				result = ideaService.updateIdea(dto);
						
				if(result >0){
					listIdea(request, response);
				}				
						

		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		} 


	}
	
	protected void deleteIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		IdeaService ideaService = new IdeaService();
		Integer result = null;
		Integer id = 
				Integer.parseInt(request.getParameter("cod"));
		
		try {
			result = ideaService.deleteIdea(id);
			
			if(result>0)
				listIdea(request, response);
			
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	
	}
	
	protected void findIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		IdeaService ideaService = new IdeaService();
		IdeaDTO dto = null;
		
		Integer id = 
				Integer.parseInt(request.getParameter("cod"));
		
		
		try {
			dto = ideaService.getIdeaById(id);		
			
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		request.setAttribute("bean", dto);
		
		RequestDispatcher rd =
				getServletContext().
				getRequestDispatcher("/jsp/editaIdea.jsp");
			rd.forward(request, response);
	}

	protected void buscaIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		IdeaService ideaService = new IdeaService();
		IdeaDTO dto = null;
		
		Integer id = 
				Integer.parseInt(request.getParameter("codigo"));
		
		
		try {
			dto = ideaService.getIdeaById(id);		
			
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		System.out.println("Ingreso busca idea!!");
		HttpSession session = request.getSession(false);
		session.setAttribute("codigoIdea", dto.getIdeaId());
		session.setAttribute("titulo", dto.getTitulo());
		session.setAttribute("descipcion", dto.getDescripcion());
		session.setAttribute("clave1", dto.getPalabraClave1());
		session.setAttribute("clave2", dto.getPalabraClave2());
		session.setAttribute("clave3", dto.getPalabraClave3());
		session.setAttribute("clave4", dto.getPalabraClave4());
		/*
		RequestDispatcher rd =
				getServletContext().
				getRequestDispatcher("/jsp/publicarIdea.jsp");
			rd.forward(request, response);
			*/
		response.sendRedirect("jsp/publicarIdea.jsp");
	}

	protected void listIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		IdeaService ideaService = new IdeaService();
		ArrayList<IdeaDTO> lstIdea = new ArrayList<IdeaDTO>();
		
		String titulo = null;
		String estado = request.getParameter("cboEstado");
		 titulo = request.getParameter("txtTitulo");
		 System.out.println("Parameter:"+titulo);
		 
		try {
			if(titulo!=null)
				lstIdea = ideaService.listIdea(titulo, estado);
			else	
				lstIdea = ideaService.listIdea("", estado);
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
				
		request.setAttribute("ideas", lstIdea);
			
		RequestDispatcher rd =
		getServletContext().
		getRequestDispatcher("/jsp/listarIdeas.jsp");
		rd.forward(request, response);
	}
	
	protected void listFiltroIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		IdeaService ideaService = new IdeaService();
		ArrayList<IdeaDTO> lstIdea = new ArrayList<IdeaDTO>();
		
		String titulo = null;
		 titulo = request.getParameter("txtTitulo");
		 System.out.println("Parameter:"+titulo);
		 
		try {
			if(titulo!=null)
				lstIdea = ideaService.listIdeaNoPublicado(titulo);
			else	
				lstIdea = ideaService.listIdeaNoPublicado("");
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
				
		request.setAttribute("ideas", lstIdea);
			
		RequestDispatcher rd =
		getServletContext().
		getRequestDispatcher("/jsp/buscarIdeas.jsp");
		rd.forward(request, response);
	}
	
	protected void listPublicadosIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		IdeaService ideaService = new IdeaService();
		ArrayList<IdeaDTO> lstIdea = new ArrayList<IdeaDTO>();
		
		String titulo = null;
		 titulo = request.getParameter("txtTitulo");
		 System.out.println("Parameter:"+titulo);
		 
		try {
			if(titulo!=null)
				lstIdea = ideaService.listIdeaPublicadas(titulo);
			else	
				lstIdea = ideaService.listIdeaPublicadas("");
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
				
		request.setAttribute("ideas", lstIdea);
			
		RequestDispatcher rd =
		getServletContext().
		getRequestDispatcher("/jsp/buscarIdeasPublicadas.jsp");
		rd.forward(request, response);
	}
	
	protected void buscaPublicadoIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		IdeaService ideaService = new IdeaService();
		IdeaDTO dto = null;
		UsuarioService usuarioservice = new UsuarioService();
		ArrayList<UsuarioDTO> lstDocentes = null;
		
		Integer id = 
				Integer.parseInt(request.getParameter("codigo"));
		
		
		try {
			dto = ideaService.getIdeaById(id);		
			lstDocentes = usuarioservice.listDocentes();
			
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		System.out.println("Ingreso busca idea!!");
		request.setAttribute("docentes", lstDocentes);
		
		HttpSession session = request.getSession(false);
		session.setAttribute("codigoIdea", dto.getIdeaId());
		session.setAttribute("titulo", dto.getTitulo());
		session.setAttribute("descipcion", dto.getDescripcion());
		session.setAttribute("clave1", dto.getPalabraClave1());
		session.setAttribute("clave2", dto.getPalabraClave2());
		session.setAttribute("clave3", dto.getPalabraClave3());
		session.setAttribute("clave4", dto.getPalabraClave4());
		
		RequestDispatcher rd =
				getServletContext().
				getRequestDispatcher("/jsp/evaluarIdea.jsp");
			rd.forward(request, response);
			
		//response.sendRedirect("jsp/evaluarIdea.jsp");
	}
	
	protected void updateEvaluarIdea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		IdeaService ideaService = new IdeaService();
		IdeaDTO dto = new IdeaDTO();
		Integer result = null;
		Integer codigoIdea = 
				Integer.parseInt(request.getParameter("codigoIdea"));
		String estado = request.getParameter("cboEvaluar");
		Integer codigoDocente = null;
		try {
			if(estado.equals("P")){
				codigoDocente = Integer.parseInt(request.getParameter("cboDocente"));
				dto.setDocenteId(codigoDocente);;
			}else{
				dto.setDocenteId(0);
			}
			dto.setIdeaId(codigoIdea);
			
			result = ideaService.updateEvaluarIdea(dto);
			
			if(result>0)
				listIdea(request, response);
			
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	
	}
	

    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
       
        System.out.println("content-disposition header= "+contentDisp);
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length()-1);
            }
        }
        return "";
    }

}
